package com.company.struct;

import java.util.Stack;

/**
 * @author jrue
 * @description https://leetcode-cn.com/problems/min-stack
 * @description https://leetcode-cn.com/explore/interview/card/top-interview-questions-easy/24/design/59/
 * @date 2019/11/15 13:39
 * 设计一个支持 push，pop，top 操作，并能在常数时间内检索到最小元素的栈。
 *
 * push(x) -- 将元素 x 推入栈中。
 * pop() -- 删除栈顶的元素。
 * top() -- 获取栈顶元素。
 * getMin() -- 检索栈中的最小元素。
 */
public class MinStack {

    private Stack<Integer> stack;
    private int min = Integer.MAX_VALUE;
    /** initialize your data structure here. */
    public MinStack() {

        stack = new Stack<>();
    }

    public void push(int x) {
        if (min > x) {
            min = x;
        }
        stack.push(x);

    }

    public void pop() {
        Integer pop = stack.pop();
        if (pop == min) {
            if (stack.isEmpty()) min = Integer.MAX_VALUE;
            else {
                min = stack.firstElement();
                stack.forEach(e -> {
                    if (min > e) {min = e; }
                });
            }
        }
    }

    public int top() {
        return stack.peek();
    }

    public int getMin() {
        return min;
    }

    //["MinStack","push","push","push","top","pop","getMin","pop","getMin","pop","push",1top","getMin","push","top","getMin","pop","getMin"]
    //[[],[2147483646],[2147483646],[2147483647],[],[],[],[],[],[],[2147483647],[],[],[-2147483648],[],[],[],[]]
    public static void main(String[] args) {
        MinStack minStack = new MinStack();
        minStack.push(2147483646);
        minStack.push(2147483646);
        minStack.push(2147483647);
        System.out.println(minStack.top());
        minStack.pop();
        minStack.getMin();
        minStack.pop();
        minStack.getMin();
        minStack.pop();
        minStack.push(2147483647);
        minStack.top();
        minStack.getMin();
        minStack.push(-2147483648);
        minStack.top();
        minStack.getMin();
        minStack.pop();
        minStack.getMin();

    }

}
